package com.company.cloud.work.modules.mgr.service.impl;


import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.LocalDateTimeUtils;
import com.company.cloud.common.utils.StrSplitUtils;
import com.company.cloud.work.constant.CrmWorkConstant;
import com.company.cloud.work.modules.base.entity.TaskExeInfo;
import com.company.cloud.work.modules.base.entity.TaskInfo;
import com.company.cloud.work.modules.base.service.TaskExeInfoService;
import com.company.cloud.work.modules.base.service.TaskInfoService;
import com.company.cloud.work.modules.mgr.controller.req.WorkTaskExeParam;
import com.company.cloud.work.modules.mgr.controller.req.WorkTaskSaveParam;
import com.company.cloud.work.modules.mgr.controller.req.WorkTaskUpdateParam;
import com.company.cloud.work.modules.mgr.service.WorkTaskMgrService;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class WorkTaskMgrServiceImpl implements WorkTaskMgrService {


    @Autowired
    private TaskInfoService taskInfoService;
    @Autowired
    private TaskExeInfoService taskExeInfoService;



    @Transactional
    @Override
    public void add(WorkTaskSaveParam params, LoginSimpleUserInfo userInfo) {
        ValidatorUtils.validate(params);
        TaskInfo entity=new TaskInfo();
        entity.setCompanyNo(userInfo.getCompanyNo());
        entity.setUserId(userInfo.getId());
        entity.setTitle(params.getTitle());
        entity.setRemark(params.getRemark());
        entity.setRunUserIds(StrSplitUtils.list2string_prefix(params.getRunUserIds()));
        entity.setCompleteDate(LocalDateTimeUtils.parse_yyyyMMddHHmmss(params.getCompleteDate()));
        entity.setRemindTypes(StrSplitUtils.list2string_prefix(params.getRemindTypes()));
        entity.setIsReceipt(params.getIsReceipt());
        entity.setState(CrmWorkConstant.TaskStateEnum.TS_Not.getCode());
        entity.addCreateParam(userInfo);
        entity.addEditParam(userInfo);
        taskInfoService.save(entity);

        List<TaskExeInfo> taskExeInfoList = new ArrayList<>();
        params.getRunUserIds().forEach(runUserId->{
            TaskExeInfo exeInfo=new TaskExeInfo();
            exeInfo.setCompanyNo(entity.getCompanyNo());
            exeInfo.setTaskId(entity.getId());
            exeInfo.setExeUserId(runUserId);
            exeInfo.setExeState(CrmWorkConstant.TaskExeStateEnum.TES_Not.getCode());
            exeInfo.setExeDate(LocalDateTime.now());
            entity.addCreateParam(userInfo);
            entity.addEditParam(userInfo);
            taskExeInfoList.add(exeInfo);
        });
        if(taskExeInfoList.size()>0){
            taskExeInfoService.saveBatch(taskExeInfoList);
        }

    }

    @Transactional
    @Override
    public void update(WorkTaskUpdateParam params, LoginSimpleUserInfo userInfo) {
        ValidatorUtils.validate(params);
        TaskInfo entity=taskInfoService.getById(params.getId());
        if (entity == null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }

        if(!CrmWorkConstant.TaskStateEnum.TS_Not.getCode().equals(entity.getState())){
            //todo 定义错误码
            throw new BusinessException("执行中任务不能修改");
        }

        entity.setTitle(params.getTitle());
        entity.setRemark(params.getRemark());
        entity.setRunUserIds(StrSplitUtils.list2string_prefix(params.getRunUserIds()));
        entity.setCompleteDate(LocalDateTimeUtils.parse_yyyyMMddHHmmss(params.getCompleteDate()));
        entity.setRemindTypes(StrSplitUtils.list2string_prefix(params.getRemindTypes()));
        entity.setIsReceipt(params.getIsReceipt());
        entity.addEditParam(userInfo);
        taskInfoService.updateById(entity);

        List<TaskExeInfo> taskExeInfoList = new ArrayList<>();
        params.getRunUserIds().forEach(runUserId->{
            TaskExeInfo exeInfo=new TaskExeInfo();
            exeInfo.setCompanyNo(entity.getCompanyNo());
            exeInfo.setTaskId(entity.getId());
            exeInfo.setExeUserId(runUserId);
            exeInfo.setExeState(CrmWorkConstant.TaskExeStateEnum.TES_Not.getCode());
            exeInfo.setExeDate(LocalDateTime.now());
            entity.addCreateParam(userInfo);
            entity.addEditParam(userInfo);
            taskExeInfoList.add(exeInfo);
        });
        if(taskExeInfoList.size()>0){
            taskExeInfoService.remove(new QueryWrapper<TaskExeInfo>().eq("task_id",entity.getId()));
            taskExeInfoService.saveBatch(taskExeInfoList);
        }
    }

    @Transactional
    @Override
    public void exe(WorkTaskExeParam params, LoginSimpleUserInfo userInfo) {
        ValidatorUtils.validate(params);
        TaskExeInfo entity=taskExeInfoService.getById(params.getTaskExeId());
        if (entity == null) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }

        if(entity.getExeState().equals(params.getExeState())){
            return ;
        }

        TaskInfo task=taskInfoService.getById(entity.getTaskId());
        if (task == null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(task.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }

        entity.setExeState(params.getExeState());
        entity.setExeRemark(params.getExeRemark());
        entity.setExeDate(LocalDateTime.now());
        entity.addEditParam(userInfo);
        taskExeInfoService.updateById(entity);

        List<TaskExeInfo> taskExeInfoList = taskExeInfoService.list(new QueryWrapper<TaskExeInfo>().eq("task_id",entity.getTaskId()));

        String exeState=null;
        if(!CollectionUtils.isEmpty(taskExeInfoList)){
            for(TaskExeInfo taskExeInfo:taskExeInfoList){
                if(exeState==null){
                    exeState=taskExeInfo.getExeState();
                }else if(!exeState.equals(taskExeInfo.getExeState())){
                    exeState= CrmWorkConstant.TaskExeStateEnum.TES_Ing.getCode();
                    break;
                }
            }
        }

        if(task.getStartDate()==null) {
            task.setStartDate(LocalDateTime.now());
        }
        if(task.getEndDate()==null) {
            task.setEndDate(LocalDateTime.now());
        }
        task.setState(exeState);
        task.addEditParam(userInfo);
        taskInfoService.updateById(task);






    }


}
